package de.wittekind.bundesjugendspiele.client.management;

import java.io.*;
import java.rmi.RemoteException;
import java.rmi.registry.*;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import de.wittekind.bundesjugendspiele.client.management.conf.Constants;
import de.wittekind.bundesjugendspiele.client.management.ui.UIController;
import de.wittekind.bundesjugendspiele.server.impl.SQLRiegenLoader;
import de.wittekind.bundesjugendspiele.server.interfaces.RiegenLoader;
import de.wittekind.bundesjugendspiele.server.mysql.OpenShiftMySQLConnectionManager;

//- testing -----------------------------

public class Management {

	private static UIController ui;
	static String host;
	private static RiegenLoader loader;

	public static void main(String[] args) {

		initLog();
		host = de.wittekind.bundesjugendspiele.server.interfaces.Constants.SERVER_HOST;
		for (int i = 0; i < args.length; i++) {
			if ("-d--debug--DEBUG".contains(args[i])) {
				de.wittekind.bundesjugendspiele.client.management.conf.Constants.DEBUG = true;
			}
			if ("-h--host".contains(args[i])) {
				i++;
				host = args[i];
				System.out.println("host manually set to:" + host + "\n");
			}

		}

		ui = new UIController();

		while (!createConnection())
			;

		ui.openWindow(loader);
	}

	private static void initLog() {
		System.out.println(System.getProperty("user.dir") + "/admin.log");
		File file = new File(System.getProperty("user.dir") + "/admin.log");
		PrintStream printStream = null;
		try {
			printStream = new PrintStream(new FileOutputStream(file, true));
		} catch (FileNotFoundException e1) {
			System.out.println("this shouldn't be happening");
		}
		// System.setOut(printStream);
		// System.setErr(printStream);
		System.out.println("\n*******************\n\nAdmin Client started.");
	}

	private static boolean createConnection() {
		String url = JOptionPane
				.showInputDialog("MySQL-URL angeben. (\"\" für RMI.)");
		if (url.length() > 0) {
			try {
				OpenShiftMySQLConnectionManager.initLocal(url);
				System.out.println(OpenShiftMySQLConnectionManager
						.getConnection());
				loader = new SQLRiegenLoader();
			} catch (Exception ex) {
				ui.showError(ex.getMessage());
				return false;
			}
		} else {
			String name = de.wittekind.bundesjugendspiele.server.interfaces.Constants.RMI_NAME;
			int port = de.wittekind.bundesjugendspiele.server.interfaces.Constants.REGISTRY_PORT;
			Registry registry;
			try {
				registry = LocateRegistry.getRegistry(host, port);
				loader = (RiegenLoader) registry.lookup(name);

			} catch (RemoteException e) {
				e.printStackTrace();
				return !ui.showError(Constants.msg
						.getString("serverNotConnected"));
			} catch (Exception e) {
				ui.showError(e.getMessage());
				return false;
			}
		}
		return true;
	}
}
